//2 words per sec
var element; 
var constraint_w=350;
var temp_param;
var flag;
var elegible;
var elegible_main=null;
var imges_main=null;
var abs_h=window.innerHeight;
var cant_read=["HTML","HEAD","SCRIPT","STYLE","META","LINK","BODY"];
var show="";
var count_coma_fulstop;
var count_hyp;
var not_count_hyp;
var has_body_changed;
var asdfg;
var zxcvb;
var handle;
var prev_time;
var amount_word=500;
var amount_time;
var flag_list=0;
var freeze=0;
var num_chng=0;
var loop_chk;
var imges;
var max_h;
var min_h;
var curr_word;
var max_word;
$(window).focus(function()
{
	freeze=0;
	if(flag_list==0)
	{
		var d=new Date();
		d=d.getTime();
		prev_time=d;
		amount_time=0;
		flag_list=1;
		make_list();
	}
	var d=new Date();
	amount_time=amount_time+d.getTime()-prev_time;
	prev_time=d.getTime();
	recording();
});
$(window).blur(function()
{
	var d=new Date();
	amount_time=amount_time+d.getTime()-prev_time;
	freeze=1;
	after_recording();
});
$(window).scroll(function()
{
	clearTimeout(handle);
	handle=setTimeout("var d=new Date();d=d.getTime();amount_time=amount_time+d-prev_time;after_recording();recording();",1500);
});
window.onbeforeunload=function()
{
	after_recording();
	freeze=1;
	makePost();
}
function update_list()
{
	if((has_body_changed!=document.body.innerHTML)&&(freeze==0))
	{
		num_chng++;
		make_list();
	}
	setTimeout("update_list();",5000);
}

function makePost()
{
	var d1=new Date();
	d1=d1.getTime();
	amount_time=amount_time+d1-prev_time;
	amount_time=amount_time/1000;
	if(isNaN(amount_time)==true)
		return;
	if((amount_time*5)<amount_word)
		amount_word=amount_time*5;
	var ee;
	var post=new Array();
	var len=elegible_main.length;
	elegible_main=elegible_main.sort(sort_list1);
	ee=0;
	var sum_param=0;
	curr_word=0;
	max_word=amount_word;
	while(ee<len)
	{
		sum_param=sum_param+elegible_main[ee].param;
		var post_txt="";
		if(elegible_main[ee].time_spent*5<elegible_main[ee].len)
		{
			post_txt=node_text(elegible_main[ee].ele);
		}
		else
		{
			post_txt=(elegible_main[ee].ele).outerHTML;
			curr_word=curr_word+no_words(elegible_main[ee].ele.innerText)
		}
		var temp_main=new Object();
		temp_main.param=elegible_main[ee].param;
		temp_main.txt=elegible_main[ee].ele.outerHTML;
		temp_main.txt1=post_txt;
		if(elegible_main[ee].ele.tagName=='LI')
			temp_main.txt='<ul>'+temp_main.txt+'</ul>';
		temp_main.ht=$(elegible_main[ee].ele).offset().top;
		temp_main.size=$(elegible_main[ee].ele).height();
		post.push(temp_main);
		ee++;
	}
	var oeoe=post.length;
	for(var i = 0; i < imges_main.length; i++){
		post[i+oeoe]=new Object();
		post[i+oeoe].src=imges_main[i].ele.getAttribute('src');
		post[i+oeoe].ht=imges_main[i].ht;
	}
	post=post.sort(sort_list2);
	var to_send=new Object();
	to_send.pos=post;
	to_send.hyp=$(location).attr('href');
	to_send.sum=sum_param;
	var port = chrome.extension.connect({name: "knockknock"});
	port.postMessage(to_send);
}

function sort_list1(a,b)
{
	return (a.param1-b.param1);
}
function sort_list2(a,b)
{
	return (a.ht-b.ht);
}
function after_recording()
{
	var d1=new Date();
	var d=d1.getTime();
	d=d-prev_time;
	prev_time=d1.getTime();
	if(elegible==undefined)
	{
		return;
	}
	if(imges_main==null)
		imges_main=new Array();
	if(elegible_main==null)
		elegible_main=new Array();
	var ee;
	var len=elegible_main.length;
	var matched=0;
	for(var j=0;j<len;j++)
	{
		for(ee=0;ee<elegible.length;ee++)
		{
			if(elegible_main[j].ele==elegible[ee].ele)
			{
				matched++;
				elegible_main[j].time_spent=elegible_main[j].time_spent+d/1000;
				elegible_main[j].param1=elegible_main[j].param1+(d/1000)*elegible[ee].param;
				elegible.splice(ee,1);
			}
		}
		if(matched==10)
			break;
	}
	for(ee=0;ee<elegible.length;ee++)
	{
		var temp=elegible[ee];
		temp.time_spent=d/1000;
		temp.param1=(d/1000)*elegible[ee].param;
		elegible_main.push(temp);
		appendInlineStyle(elegible_main[ee].ele);
	}
	if(imges==undefined)
	{
		elegible=undefined;
		return;
	}
	len=imges_main.length;
	for(var j=0;j<len;j++)
	{
		for(ee=0;ee<imges.length;ee++)
		{
			if(imges_main[j].ele==imges[ee])
			{
				matched++;
				imges.splice(ee,1);
			}
		}
	}
	for(ee=0;ee<imges.length;ee++)
	{
		var temp=new Object();
		temp.ele=imges[ee];
		temp.ht=$(imges[ee]).offset().top;
		imges_main.push(temp);
	}
	elegible=undefined;
	imges=undefined;
}
function recording()
{
	asdfg=0;/*counter for the highlight function*/
	var d=new Date();
	var param_w=0.4;	//focus distance as percentage
	var param_h=0.2;
	var abs_w=window.innerWidth;
	abs_h=window.innerHeight;
	var abs_area=abs_w*abs_h;
	var rel_h=param_h*abs_h;
	var rel_w=param_w*abs_w;
	var amount_scroll= $(window).scrollTop();
	var need=parseInt(amount_scroll/100);
	var t=1;
	var constraint_h=0;
	var perfect_points_height=amount_scroll+rel_h;
	imges=new Array();
	temp_param=1000000000;	//was 100 prev
	flag=0;
	count_coma_fulstop=0;
	loop_chk=0;
	count_hyp=0;
	not_count_hyp=0;
	var ngo=new Date();
	ngo=ngo.getTime();
	if(element==undefined)
		make_list();
	for(var ee=0;ee<=parseInt(abs_h/100);ee++)
	{
		if(element[need+ee]!=undefined)
			work(element[need+ee],constraint_h,constraint_w,amount_scroll,abs_h,abs_w,abs_area,flag,perfect_points_height,rel_w);
	}
	var bgo=new Date();
	bgo=bgo.getTime();
	
	if(elegible!=null)
	{
		for(var ee=0;ee<elegible.length;ee++)
		{
			if(max_h==null)
				max_h=elegible[ee].ele.clientHeight+$(elegible[ee].ele).offset().top;
			else if(max_h<($(elegible[ee].ele).offset().top+elegible[ee].ele.clientHeight))
				max_h=elegible[ee].ele.clientHeight+$(elegible[ee].ele).offset().top;
			if(min_h==null)
				min_h=$(elegible[ee].ele).offset().top;
			else if(min_h>$(elegible[ee].ele).offset().top)
				min_h=$(elegible[ee].ele).offset().top;
		}
		if(max_h>(amount_scroll+abs_h))
			max_h=amount_scroll+abs_h;
		if(min_h<amount_scroll)
			min_h=amount_scroll;
	}
	else
	{
		max_h=amount_scroll+abs_h;
		min_h=amount_scroll;
	}
	if(imges!=null)
	{
		imges=removeDuplicateElement(imges);//show1();
		for(var ee=0;ee<imges.lenght;ee++)
		{
			if(!($(imges[ee]).offset().top>min_h&&(($(imges[ee]).offset().top+imges[ee].clientHeight)>max_h)))
			{
				var up=$(imges[ee]).offset().top-min_h;
				var down=$(imges[ee]).offset().top+imges[ee].clientHeight-max_h;
				if(up<0)
					up=0;
				if(down<0)
					down=0;
				up=up+down;
				up=up/imges[ee].clientHeight;
				if(up>.1)
					imges.splice(ee,1)
			}
		}
	}
	var k=new Date();
	show="";
}
function removeDuplicateElement(arrayName)
{
	var newArray=new Array();
	label:for(var i=0; i<arrayName.length;i++ )
	{  
		for(var j=0; j<newArray.length;j++ )
		{
			if(newArray[j]==arrayName[i]) 
				continue label;
		}
		newArray[newArray.length] = arrayName[i];
	}
	return newArray;
}
function show1()
	{
	if(asdfg<5)
		if(elegible[asdfg]==null||elegible[asdfg]==undefined)
			{}
		else
			{
			if(asdfg>0)
				$(elegible[zxcvb].ele).css({'background-color' : 'white', 'font-weight' : 'normal'});
			$(elegible[asdfg].ele).css({'background-color' : 'IndianRed ', 'font-weight' : 'bolder'});
			zxcvb=asdfg;
			}
	if(asdfg==5)
		{
		$(elegible[zxcvb].ele).css({'background-color' : 'white', 'font-weight' : 'normal'});
		return;
		}
	asdfg++;
	setTimeout("show1()",500);
	}
$(document).ready(function()
	{
	call_makePost();
	if(document.hasFocus()==true)
		{
		make_list();
		flag_list=1;
		amount_time=new Date();
		amount_time=amount_time.getTime();
		prev_time=amount_time;
		amount_time=0;
		setTimeout('recording();',1000);
		update_list();
		}
	});
function make_list()
{
	element=undefined;
	element=new Array();
	var objArr = document.getElementsByTagName('*');
	var to_comp=/[\S]+/g;
	/* change text nodes to span begin*/
	for(var i=0;i<objArr.length;i++) 
	{
		if(objArr[i].clientHeight>(abs_h*1.5))
		{
			var temp_aray=objArr[i].childNodes;
			var txt="";
			
			if(objArr[i].tagName=='CANVAS'||temp_aray.length<=1||temp_aray==null)
				continue;
			var flagChanged = 0;
			for(var k=0;k<temp_aray.length;k++)
			{
				if(temp_aray[k].nodeType==3&&temp_aray[k].nodeValue.match(to_comp))
				{
					var nxt=temp_aray[k].nextSibling;
					txt=objArr[i].removeChild(temp_aray[k]);
					var sp=document.createElement("span");
					sp.appendChild(txt);
					objArr[i].insertBefore(sp,nxt)
				}
			}
		}
	}
	/* change text nodes to span end*/
	objArr = document.getElementsByTagName('*');
	has_body_changed=document.body.innerHTML;
	for(var i=0;i<objArr.length;i++) 
	{
		if(objArr[i].tagName!='SPAN')
		{
			if(cant_read.indexOf(objArr[i].tagName)!=-1||objArr[i].clientHeight>(abs_h*1.5))
				continue;
			if(objArr[i].clientWidth<=constraint_w && objArr[i].tagName!='IMG')
				continue;
		}
		var offset = $(objArr[i]).offset();
		var sto=parseInt(offset.top/100);
		var h=parseInt(objArr[i].clientHeight/100);
		for(;h>=0;h--)
		{
			if(element[sto+h]==undefined)
				element[sto+h]=new Array();
			element[sto+h].push(objArr[i]);
		}
	}
}
function work(ele,constraint_h,constraint_w,amount_scroll,abs_h,abs_w,abs_area,flag,perfect_points_height,rel_w)
{
	for(var j=0;j<ele.length;j++)
	{
		if(ele[j].clientHeight>constraint_h||ele[j].tagName=='SPAN')
		{
		if($(ele[j]).offset().top<($(window).scrollTop()+abs_h))
		{
			var temp_chk;
			var ht;
			if(ele[j].tagName=='SPAN')
			{
				var widt=ele[j].parentNode.clientWidth;
				ht=no_words(ele[j].innerHTML)/(widt/42)
				temp_chk=ht+($(ele[j]).offset()).top;
			}
			else
			{
				temp_chk=ele[j].clientHeight+($(ele[j]).offset()).top;
			}
			
			if(ele[j].tagName=='IMG')
			{
				if(!($(ele[j]).css("display")=="none"||$(ele[j]).css("visibility")=="hidden"))
				{
					var rat=$(ele[j]).height()/$(ele[j]).width();
					var width_img=$(ele[j]).width();
					if( rat>=0.25 && rat<=4 && width_img>=150 )
					{
						imges.push(ele[j]);
					}
				}
			}
			else if(amount_scroll<temp_chk/*&&temp_chk<(abs_h+amount_scroll)*/)
			{
				if($(ele[j]).css("display")=="none"||$(ele[j]).css("visibility")=="hidden")
					continue;
				var txt=ele[j].innerText;
				var txt_no=no_words(txt);
				
				if(txt_no==0)
				    continue;
				$(ele[j]).find('script').remove();
				var hyps=$(ele[j]).find('a');
				var hyp_data="";
				
				for(var i=0;i<hyps.length;i++)
					hyp_data=hyp_data+$(hyps[i]).text()+" ";
				
				
				var hyp_data_no=no_words(hyp_data);
				var hyp_wt=hyp_data_no/txt_no;
				if((txt_no-hyp_data_no)<10||hyp_data_no/txt_no>0.4)
					continue;
				
				if(hyp_wt>.8)
				    hyp_wt=0;
				
				else if(hyp_wt>.7)
				    hyp_wt=50;
				
				else if(hyp_wt>.5)
				    hyp_wt=150;
				
				else if(hyp_wt>.2)
				    hyp_wt=290;
				
				else 
				    hyp_wt=400;
				
				var dist=Math.sqrt(Math.pow(perfect_points_height-($(ele[j]).offset()).top,2)+Math.pow(rel_w-($(ele[j]).offset()).left,2));
				var widt;
				if(ele[j].tagName=="SPAN")
					widt=ele[j].parentNode.clientWidth;
				else
					widt=ele[j].clientWidth;
				widt=widt-350;
				widt=810*Math.sin((Math.PI/180)*(widt/9));
				var extra_length_b=0;
				var extra_length_a=0;
				if($(window).scrollTop()>(($(ele[j]).offset()).top))
					extra_length_a=$(window).scrollTop()-($(ele[j]).offset()).top;
				if(temp_chk>($(window).scrollTop()+abs_h))
					extra_length_b=temp_chk-$(window).scrollTop()-abs_h;
				var mulwt=extra_length_b+extra_length_a;
				if(ele[j].tagName=='SPAN')
					mulwt=mulwt/ht;
				else
					mulwt=mulwt/ele[j].clientHeight;
				var param=dist-hyp_wt-widt;
				if(mulwt!=0)
					if(param<0)
						param=param*(1-mulwt);
					else	param=param/(1-mulwt);
				var aaa;
				if(param>-100)
					continue;
				for(var m=0;m<10;m++)
				{
					aaa=1;
					if(elegible==null)
						elegible=new Array();
					if(elegible[m]==undefined||elegible[m]==null)
					{
						for(var ter=0;ter<10;ter++)
							if(elegible[ter]!=undefined)
							{
								if(elegible[ter].ele==ele[j])
								{
									aaa=0;
									break;
								}
								else if($(elegible[ter].ele).parents().index(ele[j])!=-1)
								{
									var tmp_ob=new Object();
									tmp_ob.hyptxt=hyp_data;
									tmp_ob.txt=txt;
									tmp_ob.len=txt_no;
									tmp_ob.ele=ele[j];
									tmp_ob.param=param;
									tmp_ob.widt=widt;
									tmp_ob.dist=dist;
									tmp_ob.hyp_wt=hyp_wt;
									tmp_ob.ext_len_a=extra_length_a;
									tmp_ob.ext_len_b=extra_length_b;
									elegible[ter]=tmp_ob;
									aaa=0;
								}
								else if($(ele[j]).parents().index(elegible[ter].ele)!=-1)
								{
								  	aaa=0;
								  	break;
								}
							}
						if(aaa==0)
							break;
						elegible[m]=new Object();
						elegible[m].hyptxt=hyp_data;
						elegible[m].txt=txt;
						elegible[m].len=txt_no;
					  	elegible[m].ele=ele[j];
					  	elegible[m].param=param;
						elegible[m].widt=widt;
					  	elegible[m].dist=dist;
					  	elegible[m].tt=temp_chk;
					  	elegible[m].hyp_wt=hyp_wt;
					  	elegible[m].ext_len_b=extra_length_b;
					  	elegible[m].ext_len_a=extra_length_a;
					  	break;
					}
				if(param<elegible[m].param)
					{
					for(var ter=0;ter<10;ter++)
						if(elegible[ter]!=undefined)
						{
							if(elegible[ter].ele==ele[j])
							{
								aaa=0;
								break;
							}
							else if($(elegible[ter].ele).parents().index(ele[j])!=-1)
							{
								var tmp_ob=new Object();
								tmp_ob.hyptxt=hyp_data;
								tmp_ob.txt=txt;
								tmp_ob.len=txt_no;
								tmp_ob.ele=ele[j];
								tmp_ob.param=param;
								tmp_ob.widt=widt;
								tmp_ob.dist=dist;
								tmp_ob.hyp_wt=hyp_wt;
								tmp_ob.ext_len_a=extra_length_a;
								tmp_ob.ext_len_b=extra_length_b;
								elegible[ter]=tmp_ob;
								aaa=0;
							}
							else if($(ele[j]).parents().index(elegible[ter].ele)!=-1)
							{
							  	aaa=0;
							  	break;
							}
						}
					if(aaa==0)
						break;
					var tmp_ob=new Object();
					tmp_ob.hyptxt=hyp_data;
					tmp_ob.txt=txt;
					tmp_ob.len=txt_no;
				  	tmp_ob.ele=ele[j];
				  	tmp_ob.param=param;
				  	tmp_ob.widt=widt;
				  	tmp_ob.dist=dist;
				  	tmp_ob.hyp_wt=hyp_wt;
				  	tmp_ob.tt=temp_chk;
				  	tmp_ob.ext_len_a=extra_length_a;
				  	tmp_ob.ext_len_b=extra_length_b;
				  	elegible.splice(m,0,tmp_ob);
				  	elegible.splice(10,1);
				  	break;
					}
				}
				flag=1;
			}
		}
		}
	}
}
function appendInlineStyle(node){
	var ob=new Object;
	if(node.nodeType != 1)
		return;
	var allList = node.getElementsByTagName("*");
	var property = new Array();
	var totalAttr;
	var temp;
	property[0] = "padding";
	property[1] = "margin-top";
	property[2] = "width";
	property[3] = "overflow";
	property[4] = "float";
	property[5] = "clear";
	property[6] = "font-size";
	property[7] = "height";
	property[8] = "color";
	property[9] = "background-color";
	for(i=0 ; i < allList.length; i++){
		totalAttr = allList[i].getAttribute("style"); 
		if(totalAttr == null) {
		totalAttr = "";
		}
		else{
			totalAttr += "; ";
		}
		for(j = 0;j <property.length ;j++){
			temp = window.getComputedStyle(allList[i]).getPropertyValue(property[j]);
			if(temp == ""){
				continue;
			}
			totalAttr += property[j]+":"+temp+"; ";
		}
		allList[i].setAttribute("blinkk_style", totalAttr);
	}
}
function no_words(str)
{
	str=str.split(" ");
	var c=0;
	var patt=/[A-z]/;
	for(var i=0;i<str.length;i++)
		if(str[i]!=""&&str[i].match(patt)!=null)
			c++;
	return c;
}
/*functoin to extract the node value from a subset of tree
 * initial parameters (elegible_main[ee],amount_word,0)*/
function node_text(node)	
{
	var temp_curr_word;
	var bache=node.childNodes;
	if(bache==undefined||bache.length==undefined||bache.length==0)
	{
		if(node.nodeType==3)
			{
			curr_word=curr_word+no_words(node.nodeValue);
			return node.nodeValue;
			}
		curr_word=curr_word+no_words(node.innerText);
		return node.outerHTML;
	}
	var tot_text="";
	for(var i=0;i<bache.length;i++)
	{
		temp_curr_word=curr_word;
		var txt;
		if(bache[i].nodeType!=3)
		{
			txt=bache[i].innerText;
		}
		else 
		{
			txt=bache[i].nodeValue;
		}
		var txt_no;
		if(txt!=null||txt=="")
			txt_no=no_words(txt);
		else txt_no=0;
		temp_curr_word=temp_curr_word+txt_no;
		if(temp_curr_word<max_word)
		{
			curr_word=curr_word+txt_no;
			if(bache[i].nodeType==3)
				tot_text=tot_text+txt+" ";
			else
				tot_text=tot_text+bache[i].outerHTML+" ";
			continue;
		}
		else
		{
			tot_text=tot_text+node_text(bache[i]);
			break;
		}
	}
	var patt1 = /<([a-zA-Z0-9]*)([^>]*)>/i;
	var q=(node.outerHTML).match(patt1);
	tot_text='<'+q[1]+' '+q[2]+'>'+tot_text+'</'+q[1]+'>';
	return tot_text;
}

function call_makePost()
{
	setTimeout('makePost();call_makePost();',8000);
}